package com.youlu.campus.web.community.service.impl;

import com.youlu.campus.base.base.ContentTypeEnum;
import com.youlu.campus.base.base.GeneraStatusEnum;
import com.youlu.campus.base.base.InteractiveActionEnum;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.community.dto.ArticlePageResponse;
import com.youlu.campus.web.community.dto.ArticleResponse;
import com.youlu.campus.web.community.dto.InteractiveMqRequest;
import com.youlu.campus.web.community.dto.TopicQueryRequest;
import com.youlu.campus.web.community.entity.ArticleInfo;
import com.youlu.campus.web.community.service.ArticleService;
import com.youlu.campus.web.community.service.InteractiveService;
import com.youlu.campus.web.common.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章信息接口实现类
 *
 * @author: YangJ
 * @date: 2020/12/2 18:56
 */
@Slf4j
@Service("articleService")
public class ArticleServiceImpl extends BaseService implements ArticleService {

    @Autowired
    private InteractiveService interactiveService;

    @Override
    public Page<ArticlePageResponse> articleList(TopicQueryRequest request) {

        Query query = new Query();
        query.addCriteria(Criteria.where("status").is(GeneraStatusEnum.ON.getCode()));
        query.addCriteria(Criteria.where("deleted").is(false));
        long count = mongoTemplate.count(query, ArticleInfo.class);

        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
        if (StringUtils.isNotBlank(request.getSortVal())
                && "new".equals(request.getSortVal())) {
            //TODO:
//            query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        } else {
            //TODO:
//            query.with(new Sort(Sort.Direction.DESC, "weight"));
//            query.with(new Sort(Sort.Direction.DESC, "hotCount"));
//            query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        }

        List<ArticleInfo> articleInfos = mongoTemplate.find(query.with(pageRequest), ArticleInfo.class);
        List<ArticlePageResponse> list = articleInfos.stream().map(articleInfo -> {
            ArticlePageResponse response = mapperFacade.map(articleInfo, ArticlePageResponse.class);
            List<String> avatars = interactiveService.queryLikeUser(response.getId(), ContentTypeEnum.WZ.getCode());
            if (avatars != null) {
                response.setAvatars(avatars);
            }
            response.setReadCountStr(CommonUtils.intChange2Str(response.getReadCount()));
            response.setLiked(interactiveService.queryIsLike(response.getId(), ContentTypeEnum.WZ.getCode()));
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public ArticleResponse query(String id) {
        log.info("查询文章信息开始，id:{}", id);

        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        ArticleInfo articleInfo = mongoTemplate.findOne(query, ArticleInfo.class);
        if (articleInfo == null) {
            throw new BusinessException("文章信息查询失败!");
        }
        ArticleResponse response = mapperFacade.map(articleInfo, ArticleResponse.class);
        response.setReadCountStr(CommonUtils.intChange2Str(response.getReadCount()));
        response.setLiked(interactiveService.queryIsLike(response.getId(), ContentTypeEnum.WZ.getCode()));
        response.setCollected(interactiveService.isCollect(response.getId()));
        log.info("查询文章信息结束");

        //维护文章统计信息-阅读数(+1)
        InteractiveMqRequest req = new InteractiveMqRequest();
        req.setType(ContentTypeEnum.WZ.getCode());
        req.setAction(InteractiveActionEnum.READ.getCode());
        req.setBid(id);
        req.setValue(1);
        sendMsg(req);
        return response;
    }

    private void sendMsg(InteractiveMqRequest req) {
//        mqService.sendNormal(req, CampusMQDefinition.ROUTING_KEY_INTERACTIVE);
    }
}
